/**
 * Created with IntelliJ IDEA.
 * Description:
 * User: 26727
 * Date: 2024-02-03
 * Time: 18:15
 */

 public class TreeNode {
      int val;
      TreeNode left;
      TreeNode right;
      TreeNode() {}
      TreeNode(int val) { this.val = val; }
      TreeNode(int val, TreeNode left, TreeNode right) {
        this.val = val;
        this.left = left;
        this.right = right;
      }
  }

class Solution {

    public int i = 0;
    public TreeNode buildTree(int[] preorder, int[] inorder) {
        return buildTreeChild(preorder,inorder,0,inorder.length-1);
    }

    public TreeNode buildTreeChild(int[] preorder,int[] inorder,int inbegin, int inend) {

        if(inbegin > inend) {
            return null; //说明没有子树了
        }

        TreeNode root = new TreeNode(preorder[i]);

        //在中序遍历中找到当前根结点的位置
        int rootIndex = findIndex(inorder,inbegin,inend,preorder[i]);
        i++;

        root.left = buildTreeChild(preorder,inorder,inbegin, rootIndex-1);
        root.right = buildTreeChild(preorder, inorder,rootIndex+1, inend);

        return root;

    }

    public int findIndex(int[] inorder, int inbegin, int inend,int key) {
        for(int i = inbegin; i <= inend; i++) {
            if(inorder[i] == key) {
                return i;
            }
        }
        return -1;
    }

}
